<template>
  <div class="home-container">
    <div class="page-header">
      <h2 class="page-title">欢迎使用用户和新闻管理系统</h2>
      <p class="page-subtitle">高效管理用户信息和新闻内容</p>
    </div>

    <!-- 统计卡片区域 -->
    <div class="stats-cards">
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon user-icon">
            <i class="el-icon-user"></i>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ userList.length }}</div>
            <div class="stat-label">用户总数</div>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card" shadow="hover">
        <div class="stat-content">
          <div class="stat-icon news-icon">
            <i class="el-icon-document"></i>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ newsList.length }}</div>
            <div class="stat-label">新闻总数</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 用户列表区域 -->
    <el-card class="content-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h3 class="card-title">用户列表</h3>
          <div class="card-actions">
            <el-tag type="success" class="count-tag">共 {{ userList.length }} 条</el-tag>
          </div>
        </div>
      </template>
      
      <el-table 
        :data="userList" 
        style="width: 100%"
        v-loading="loadingUsers"
        empty-text="暂无用户数据"
        stripe
        border
        :header-cell-style="{ backgroundColor: '#fafafa', fontWeight: 600 }"
        :row-style="{ transition: 'all 0.2s ease' }"
        @row-hover="handleRowHover"
      >
        <el-table-column prop="id" label="用户ID" width="80" align="center" />
        <el-table-column prop="name" label="用户名" width="180">
          <template #default="scope">
            <div class="user-name">
              <span class="name-text">{{ scope.row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" show-overflow-tooltip />
        <el-table-column prop="age" label="年龄" width="80" align="center">
          <template #default="scope">
            <el-tag :type="getAgeTagType(scope.row.age)">{{ scope.row.age }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180" align="center">
          <template #default="scope">
            <span class="time-text">{{ formatDate(scope.row.created_at) }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新闻列表区域 -->
    <el-card class="content-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h3 class="card-title">最新新闻</h3>
          <div class="card-actions">
            <router-link to="/news" class="view-all-link">
              查看全部 <i class="el-icon-arrow-right"></i>
            </router-link>
          </div>
        </div>
      </template>

      <div class="news-list">
        <el-card 
          v-for="news in newsList.slice(0, 4)" 
          :key="news.id" 
          class="news-card"
          @click="goToNewsDetail(news.id)"
          shadow="hover"
        >
          <template #header>
            <div class="news-header">
              <h3 class="news-title">{{ news.title }}</h3>
              <el-tag size="small" class="author-tag">{{ news.author }}</el-tag>
            </div>
          </template>
          <div class="news-content">
            {{ truncateContent(news.content, 120) }}
          </div>
          <template #footer>
            <div class="news-footer">
              <span class="news-time">{{ formatDate(news.created_at) }}</span>
              <el-button type="primary" size="small" link class="view-detail-btn">
                查看详情
              </el-button>
            </div>
          </template>
        </el-card>
      </div>
      <div v-if="loadingNews" class="loading-container">
        <el-skeleton :rows="3" animated />
      </div>
      <div v-if="!loadingNews && newsList.length === 0" class="empty-container">
        <el-empty description="暂无新闻数据" />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getUserList } from '../api/userAPI'
import { getNewsList } from '../api/newsAPI'

const router = useRouter()
const userList = ref([])
const newsList = ref([])
const loadingUsers = ref(false)
const loadingNews = ref(false)

// 获取用户列表数据
const fetchUsers = async () => {
  loadingUsers.value = true
  try {
    const response = await getUserList()
    userList.value = response.data || []
  } catch (error) {
    console.error('获取用户列表失败:', error)
  } finally {
    loadingUsers.value = false
  }
}

// 获取新闻列表数据
const fetchNews = async () => {
  loadingNews.value = true
  try {
    const response = await getNewsList({ page: 1, pageSize: 10 })
    newsList.value = response.data || []
  } catch (error) {
    console.error('获取新闻列表失败:', error)
  } finally {
    loadingNews.value = false
  }
}

// 跳转到新闻详情页
const goToNewsDetail = (newsId) => {
  router.push(`/news/${newsId}`)
}

// 表格行悬停处理
const handleRowHover = (row, event) => {
  // 可以在这里添加自定义的行悬停逻辑
}

// 根据年龄获取标签类型
const getAgeTagType = (age) => {
  if (age < 18) return 'info'
  if (age < 30) return 'success'
  if (age < 50) return 'warning'
  return 'danger'
}

// 格式化日期 - 添加错误处理和更健壮的日期解析
const formatDate = (dateString) => {
  // 检查输入是否有效
  if (!dateString || dateString === 'null' || dateString === 'undefined') {
    return '未知时间'
  }
  
  try {
    // 尝试解析日期，处理不同格式的日期字符串
    const date = new Date(dateString)
    
    // 检查是否是有效日期
    if (isNaN(date.getTime())) {
      return '无效时间'
    }
    
    // 使用更可靠的格式化方式
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    
    return `${year}-${month}-${day} ${hours}:${minutes}`
  } catch (error) {
    console.error('日期格式化错误:', error)
    return '时间格式错误'
  }
}

// 截断内容
const truncateContent = (content, maxLength) => {
  if (!content) return ''
  if (content.length <= maxLength) return content
  return content.substring(0, maxLength) + '...'
}

// 组件挂载时获取数据
onMounted(() => {
  fetchUsers()
  fetchNews()
})
</script>

<style scoped>
.home-container {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xl);
  animation: pageLoad 0.6s ease-out;
}

@keyframes pageLoad {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 页面标题区域 */
.page-header {
  text-align: center;
  padding: var(--spacing-xxl) 0;
  background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-active) 100%);
  color: white;
  border-radius: var(--border-radius-lg);
  margin: -var(--spacing-xl) -var(--spacing-xl) var(--spacing-xl);
  box-shadow: var(--box-shadow-dark);
}

.page-title {
  font-size: var(--font-size-xxl);
  font-weight: 700;
  margin: 0 0 var(--spacing-sm);
  letter-spacing: -0.5px;
}

.page-subtitle {
  font-size: var(--font-size-base);
  opacity: 0.9;
  margin: 0;
  font-weight: 400;
}

/* 统计卡片区域 */
.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: var(--spacing-lg);
  margin-bottom: var(--spacing-xl);
}

.stat-card {
  border-radius: var(--border-radius-base);
  transition: var(--transition-base);
  overflow: hidden;
  border: none;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: var(--box-shadow-dark);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: var(--spacing-lg);
  padding: var(--spacing-base);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.user-icon {
  background: linear-gradient(135deg, var(--info-color), var(--primary-hover));
}

.news-icon {
  background: linear-gradient(135deg, var(--success-color), #73d13d);
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 2rem;
  font-weight: 700;
  color: var(--text-primary);
  line-height: 1.2;
}

.stat-label {
  font-size: var(--font-size-sm);
  color: var(--text-secondary);
  margin-top: var(--spacing-xs);
}

/* 内容卡片 */
.content-card {
  border-radius: var(--border-radius-base);
  border: none;
  transition: var(--transition-base);
  overflow: hidden;
}

.content-card:hover {
  box-shadow: var(--box-shadow-dark);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
}

.card-title {
  font-size: var(--font-size-lg);
  font-weight: 600;
  color: var(--text-primary);
  margin: 0;
}

.card-actions {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
}

.count-tag {
  font-size: var(--font-size-xs);
  padding: 4px 10px;
}

.view-all-link {
  color: var(--primary-color);
  font-size: var(--font-size-sm);
  font-weight: 500;
  text-decoration: none;
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
  transition: var(--transition-base);
}

.view-all-link:hover {
  color: var(--primary-hover);
  transform: translateX(4px);
}

/* 用户表格 */
.time-text {
  font-size: var(--font-size-sm);
  color: var(--text-secondary);
}

.user-name {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
}

.name-text {
  font-weight: 500;
  color: var(--text-primary);
}

/* 新闻列表 */
.news-list {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: var(--spacing-lg);
}

.news-card {
  cursor: pointer;
  transition: var(--transition-base);
  border: none;
  border-radius: var(--border-radius-base);
  overflow: hidden;
}

.news-card:hover {
  transform: translateY(-6px);
  box-shadow: var(--box-shadow-dark);
}

.news-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: var(--spacing-sm);
}

.news-title {
  margin: 0;
  font-size: var(--font-size-lg);
  font-weight: 600;
  color: var(--text-primary);
  line-height: 1.4;
  flex: 1;
  transition: var(--transition-base);
}

.news-card:hover .news-title {
  color: var(--primary-color);
}

.author-tag {
  background-color: var(--primary-color) !important;
  color: white !important;
  font-size: var(--font-size-xs) !important;
  padding: 2px 8px !important;
  height: auto;
}

.news-content {
  margin: var(--spacing-base) 0;
  color: var(--text-regular);
  line-height: 1.7;
  font-size: var(--font-size-sm);
}

.news-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: var(--text-secondary);
  font-size: var(--font-size-sm);
}

.news-time {
  color: var(--text-secondary);
}

.view-detail-btn {
  font-size: var(--font-size-xs) !important;
  padding: 0 !important;
}

/* 加载和空状态 */
.loading-container,
.empty-container {
  padding: var(--spacing-xxl) 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    padding: var(--spacing-xl) var(--spacing-base);
    margin: -var(--spacing-base) -var(--spacing-base) var(--spacing-lg);
  }
  
  .page-title {
    font-size: var(--font-size-xl);
  }
  
  .stats-cards {
    grid-template-columns: 1fr;
    gap: var(--spacing-base);
  }
  
  .news-list {
    grid-template-columns: 1fr;
    gap: var(--spacing-base);
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: var(--spacing-sm);
  }
  
  .news-header {
    flex-direction: column;
    align-items: flex-start;
    gap: var(--spacing-xs);
  }
  
  .news-title {
    font-size: var(--font-size-base);
  }
  
  .news-footer {
    flex-direction: column;
    align-items: flex-start;
    gap: var(--spacing-xs);
  }
}
</style>